package cn.xumaoyang.org.controller;

import cn.xumaoyang.basic.util.AjaxResult;
import cn.xumaoyang.basic.util.PageList;
import cn.xumaoyang.org.domain.Type;
import cn.xumaoyang.org.query.TypeQuery;
import cn.xumaoyang.org.service.ITypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/type")
public class TypeController {

    //注入service层得接口
    @Autowired
    private ITypeService typeService;


    //传对象就用@RequestBody
    //传递值就用@PathVariable
    //在GetMapping或者DeleteMapping需要在（"/{}"）写上前端传递过来得类型。


    /**
     * 写接口的三要素：
     *   1.请求的地址是什么   http://localhost:8080/dept/1  delete;
     *   2.请求的参数是什么  /{id}
     *   3.返回值是什么  AjaxResult
     * @param
     */


    //查询单个
    @GetMapping("/{id}")
    public Type get(@PathVariable("id") Long id) {
        return typeService.loadById(id);
    };

    //查询所有
    @GetMapping
    public List<Type> findAll(){
        return typeService.loadAll();
    };

    //新增和修改
    @PutMapping
    public AjaxResult addUpdete(@RequestBody Type employee){
        try {
            //增加和修改一起写需要根据id来判断
            if (employee.getId() == null){
                typeService.add(employee);
            }else {
                typeService.update(employee);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败"+e.getMessage());
        }
    };
    //删除
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") long id){
        try {
            typeService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败"+e.getMessage());
        }
    };

    //批量删除
    @PatchMapping
    public AjaxResult deletes(@RequestBody List<Long> ids){   //类似对象集合类型得就使用@RequestBody注解。
        try {
            typeService.deletes(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败"+e.getMessage());
        }
    };


    //分页和高级查询
    @PostMapping
    public PageList<Type> queryPage(@RequestBody TypeQuery query){
        return typeService.queryPage(query);
    };
}
